package com.example.news.controller;

import com.example.news.pojo.Comments;
import com.example.news.pojo.News;
import com.example.news.pojo.PageResult;
import com.example.news.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@CrossOrigin
public class NewsController {
    @Autowired
    private NewsService newsService;

//    @RequestMapping("/index")
//    public String getAllNews(String title, Model model){
//        model.addAttribute("newsList",newsService.getAllNews(title));
//        System.out.println(title);
//        return "index";
//    }

    @RequestMapping("/index")
    public String getAllNews(Integer pageNo, String title, Model model){
        Integer currentPage = pageNo == null ? 1 : pageNo;
        System.out.println("title:"+title);
        PageResult<News> pageResult = newsService.getAllNews(currentPage, title);
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("title", title);
        return "index";
    }

    @RequestMapping("/showDetail")
    public String showNewsDetail(String newsCode, Model model){
        //准备两个sql
        System.out.println(newsCode);
        News news = newsService.showNewsDetail(newsCode);
        List<Comments> commentsList = newsService.getComments(newsCode);
        model.addAttribute("news", news);
        model.addAttribute("commentsList", commentsList);
        model.addAttribute("newsCode", newsCode);
        return "news";
    }

    @RequestMapping("/addComments")
    public String addComments(Comments comments, Model model){
        System.out.println(comments.toString());
        String date = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
        comments.setCreateTime(date);
        newsService.addComments(comments);
        return "news";
    }

}
